<?php
declare (strict_types = 1);

namespace app\admin\controller\erp;

use app\admin\controller\AuthController;
use app\admin\model\erp\ErpAssets;
use app\admin\model\erp\ErpSubjects;
use app\admin\model\system\SystemMenus;
use app\admin\model\system\SystemRole;
use bbweb\services\UtilService as Util;
use think\Request;

class BasicsAssets extends AuthController
{
    /**
     * 显示列表
     *
     * @param  \think\Request  $req
     * @return \think\Response
     */
    public function index(Request $req)
    {
        if ($req->isAjax()) {
            $data = [];
            $page = $req->param('page/d', 1);
            $limit = $req->param('limit/d', 15);
            $query = ErpAssets::order('id DESC');

            $data['count'] = $query->count('id');
            $data['data'] = $query->page($page,$limit)->select()->toArray();
            $data['code'] = 0;
            $data['msg'] = '';
            $groups = SystemRole::getSelect();
            foreach ($data['data'] as &$val) {
                $val['group_type'] = $groups[$val['group']] ?? '--/--';
            }

            return json($data);
        }
        $sonAuth = SystemMenus::getSonAuth($req->controller(), $req->action(),array_keys($this->auth));

        // 显示页面
        $this->assign('sonAuth', $sonAuth);
        return $this->fetch();
    }

    /**
     * 创建资源.
     *
     * @param  \think\Request  $req
     * @return \think\Response
     */
    public function add(Request $req)
    {
        $id = intval($req->param('id/d'));
        if($id) {
            $asset = ErpAssets::where('id', $id)->find();
            if($asset) {
                $asset['buy_at'] = $asset['buy_at'] ? date('Y-m-d',$asset['buy_at']) : '';
            }
        } else {
            $asset = [];
        }
        if($req->isPost()) {
            $float = $req->param('float/d',4);
            $data = Util::postMore([
                ['name',''],
                ['price',0],//购进原价
                ['buy_at',''],
                ['group',0],
                ['to_code',''],
                ['market',''],
                ['month',0],//总期数
                ['old_month',0],//使用月数
                ['salvage',0],//残值率
            ], $req);
            $data['buy_at'] = preg_match("/^\d{4}-\d{1,2}-\d{1,2}$/s", $data['buy_at']) ? strtotime($data['buy_at']) : 0;
            if (!$data['name']) $this->error('请输入资产名称');
            if (!$data['to_code']) $this->error('请选择借方科目');
            if (!$data['price']) $this->error('请设置购进原价');
            if (!$data['month']) $this->error('请设置使用期限');
            if (!$data['salvage']) $this->error('请设置残值率');
            if(ErpAssets::where('name','=',$data['name'])->find()) {
                $this->error('资产名称已存在，请增加区分编号');
            }
            $data['salvage'] = round($data['salvage'], 1);
            $data['price'] = round($data['price'], 2);
            $data['update_at'] = time();
            $salvage = round(((1 - $data['salvage'] / 100) / $data['month']),$float);
            $month_price = round(($data['price'] * $salvage), 2);//每月折旧金额
            $old_money = round($month_price * $data['old_month'], 2);
            $money = round($data['price'] - $old_money, 2);//现存价值
            $data['money'] = $money;
            $data['month_price'] = $month_price;

            $sub = ErpSubjects::where('code', '=', '1013')->find();
            if(!$sub) $this->error('没有找到对应会计科目');
            $level = $sub['level'] + 1;
            $code = ErpSubjects::where('code','like', "{$sub['code']}%")->where('level',$level)->max('code');
            if($code <= $sub['code']) $code = $sub['code'] . '000';
            $code = $code + 1;
            $data['code'] = substr((string) $code, 4);

            $zsub = ErpSubjects::where('code', '=', '1014')->find();
            if(!$zsub) $this->error('没有找到累计折旧会计科目');
            $zlevel = $zsub['level'] + 1;
            $zcode = ErpSubjects::where('code','like', "{$zsub['code']}%")->where('level',$zlevel)->max('code');
            if($zcode <= $zsub['code']) $zcode = $zsub['code'] . '000';
            $zcode = $zcode + 1;

            ErpAssets::beginTrans();
            try {
                $res = ErpAssets::create($data);
                if($res && $res->id) {
                    $info = $res->toArray();
                    $item = [
                        'pid'       => $sub['id'],
                        'rel_id'    => $info['id'],
                        'rel_type'  => 'acca',
                        'code'      => $code,
                        'name'      => $info['name'],
                        'pname'     => $sub['pname'],
                        'level'     => $level,
                        'luck'      => 1,
                        'edit_luck' => 1,
                        'update_at' => time()
                    ];
                    $sb = ErpSubjects::create($item);
                    if(!$sb) {
                        throw new \think\Exception('固定资产下会计科目写入失败！');
                    }

                    $zitem = [
                        'pid'       => $zsub['id'],
                        'rel_id'    => $info['id'],
                        'rel_type'  => 'accb',
                        'code'      => $zcode,
                        'name'      => $info['name'],
                        'pname'     => $zsub['pname'],
                        'level'     => $zlevel,
                        'luck'      => 1,
                        'edit_luck' => 1,
                        'update_at' => time()
                    ];
                    $zsb = ErpSubjects::create($zitem);
                    if(!$zsb) {
                        throw new \think\Exception('累计折旧下会计科目写入失败！');
                    }
                } else {
                    throw new \think\Exception('保存失败！');
                }
                ErpAssets::commitTrans();
            } catch (\Exception $e) {
                ErpAssets::rollbackTrans();
                $this->error($e->getMessage());
            }
            $this->success('操作成功!');
        }
        $groups = SystemRole::getSelect();
        $this->assign('groups',$groups);
        $this->assign('asset',$asset);
        return $this->fetch();
    }

    /**
     * 更新资源
     *
     * @param  \think\Request  $req
     * @return \think\Response
     */
    public function edit(Request $req)
    {
        $id = intval($req->param('id/d'));
        if(!$id) $this->error('参数错误','', -1);
        $asset = ErpAssets::where('id', $id)->find();
        if(!$asset) $this->error('参数错误','', -1);
        if($req->isPost()) {
            $float = $req->param('float/d',4);
            $data = Util::postMore([
                ['name',''],
                ['price',0],//购进原价
                ['buy_at',''],
                ['group',0],
                ['to_code',''],
                ['market',''],
                ['month',0],//总期数
                ['old_month',0],//使用月数
                ['salvage',0],//残值率
            ], $req);
            $data['buy_at'] = preg_match("/^\d{4}-\d{1,2}-\d{1,2}$/s", $data['buy_at']) ? strtotime($data['buy_at']) : 0;
            if (!$data['name']) $this->error('请输入资产名称');
            if (!$data['to_code']) $this->error('请选择借方科目');
            if (!$data['price']) $this->error('请设置购进原价');
            if (!$data['month']) $this->error('请设置使用期限');
            if (!$data['salvage']) $this->error('请设置残值率');
            $sub_up = $asset['name'] != $data['name'] ? true : false;
            if($sub_up && ErpAssets::where('name','=',$data['name'])->where('id','<>',$id)->find()) {
                $this->error('资产名称已存在，请增加区分编号');
            }
            $data['salvage'] = round($data['salvage'], 1);
            $data['price'] = round($data['price'], 2);
            $data['update_at'] = time();
            $salvage = round(((1 - $data['salvage'] / 100) / $data['month']),$float);
            $month_price = round(($data['price'] * $salvage), 2);//每月折旧金额
            $old_money = round($month_price * $data['old_month'], 2);
            $money = round($data['price'] - $old_money, 2);//现存价值
            $data['money'] = $money;
            $data['month_price'] = $month_price;

            $sub = ErpSubjects::where('rel_id', '=', $id)->where('rel_type','=','acca')->find();
            if(!$sub) $this->error('没有固定资产下对应会计科目');

            $zsub = ErpSubjects::where('rel_id', '=', $id)->where('rel_type','=','accb')->find();
            if(!$zsub) $this->error('没有累计折旧下对应会计科目');
            ErpAssets::beginTrans();
            try {
                $res = ErpAssets::where('id', $id)->update($data);
                if($res) {
                    $item = [
                        'name'      => $data['name'],
                        'update_at' => time()
                    ];
                    if($sub_up) {
                        $sb = ErpSubjects::where('rel_id', $id)->where('rel_type','=','acca')->update($item);
                        if (!$sb) {
                            throw new \think\Exception('对应资产下会计科目修改失败！');
                        }
                        $zsb = ErpSubjects::where('rel_id', $id)->where('rel_type','=','accb')->update($item);
                        if (!$zsb) {
                            throw new \think\Exception('对应折旧下会计科目修改失败！');
                        }
                    }
                } else {
                    throw new \think\Exception('保存失败！');
                }
                ErpAssets::commitTrans();
            } catch (\Exception $e) {
                ErpAssets::rollbackTrans();
                $this->error($e->getMessage());
            }
            $this->success('操作成功!');
        }
        $asset['buy_at'] = $asset['buy_at'] ? date('Y-m-d',$asset['buy_at']) : '';
        $groups = SystemRole::getSelect();
        $this->assign('groups',$groups);
        $this->assign('asset',$asset);
        return $this->fetch();
    }
}
